import websocket
import threading
import json

class Service:

    def __init__(self, framework):
        self._framework = framework
        self.service = None
        self.service_status = False
        self.service_task = threading.Thread(name="service_task", target=self.task)
        self.service_task.daemon = True
        self.service_task.start()
    
    # 消息服务任务
    def task(self):
        websocket.enableTrace(False)
        self.service = websocket.WebSocketApp("ws://127.0.0.1:10081", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)
        self.service.on_open = self.on_open
        self.service.run_forever()
    
    # 向消息服务发送消息
    def write(self, message):
        if self.service is not None and self.service_status:
            self.service.send(json.dumps(message))

    # 打开消息服务
    def on_open(self, ws):
        self.service_status = True
    
    # 收到消息服务发来的信息
    def on_message(self, ws, message):
        message_json = json.loads(message)
        # 收到消息服务发送来的消息
        if message_json["operate"]:
            pass
    
    # 消息服务出现错误时
    def on_error(self, ws, error):
        self.service = None

    # 消息服务关闭时
    def on_close(self, ws):
        self.service = None
    
